from datetime import datetime

from flask import Blueprint, request, render_template, session, redirect
from utils.verify_rule import str_is_blank
from utils.encrypt import *
from utils.errorResponse import errorResponse
from model.User import User
from db import db

# 蓝图，类似于spring boot中的controller
user_bp = Blueprint(
    "user",
    __name__,
    url_prefix="/user",
    template_folder="templates",
    static_folder="static",
)


@user_bp.route("/login", methods=["GET", "POST"])
def login():
    """
    用户登录，验证用户名和密码是否正确
    登录成功后，会保存用户名在session中，并更新用户的最后登录时间
    :return:
    """
    if request.method == "POST":
        # 验证用户名和密码是否正确
        username = request.form["username"]
        password = request.form["password"]
        print(username, password)
        if str_is_blank(username) or str_is_blank(password):
            return errorResponse("用户名或密码不能为空！")
        user = User.query.filter_by(username=username).first()
        if user is None:
            return errorResponse("用户名或密码错误！")
        if not sha256_verify(password, user.password):
            return errorResponse("用户名或密码错误！")
        if user.is_active == 0:
            return errorResponse("该用户已被禁用！")
        # 登录成功
        session["username"] = user.username

        current_time = datetime.now()
        formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
        user.last_login = formatted_time
        db.session.commit()

        return redirect("/page/home")
    else:
        return render_template("login.html")


@user_bp.route("/register", methods=["GET", "POST"])
def register():
    """
    用户注册，验证用户名和密码是否正确，并保存到数据库中
    密码会进行sha256加密
    注册成功后，会保存用户名在session中，并更新用户的最后登录时间
    :return:
    """
    if request.method == "POST":
        # 验证用户名和密码是否正确
        username = request.form["username"]
        password = request.form["password"]
        repassword = request.form["repassword"]
        print(username, password)
        if str_is_blank(username) or str_is_blank(password):
            return errorResponse("用户名或密码不能为空！")
        if password != repassword:
            return errorResponse("两次输入的密码不一致！")
        user = User.query.filter_by(username=username).first()
        if user is not None:
            return errorResponse("该用户名已被注册！")

        encrypt_pwd = sha256_hash(password)
        new_user = User(username=username, password=encrypt_pwd)
        db.session.add(new_user)
        db.session.commit()
        # 登录成功
        session["username"] = username
        return redirect("/page/home")
    else:
        return render_template("register.html")


@user_bp.route("/logout")
def logout():
    """
    用户退出，清除session
    :return:
    """
    session.clear()
    return redirect("/user/login")
